const Details = require("../model/details.model.js");
const Links = require("../model/links.model.js");
const Boxes = require("../model/boxes.model.js");
const Stations = require("../model/stations.model.js");

class DetailsService {
  //保存配置
  async saveDetails({
    detailId,
    tag,
    tagId,
    detailKey,
    detailValue,
    detailType,
    dataFlag,
  }) {
    var update = false;
    var detail = {};
    var whereOpt = {};
    if (detailId && detailId > 0) {
      update = true;
      whereOpt.detailId = detailId;
    }
    linkId >= 0 && Object.assign(detail, { linkId });
    detailKey >= 0 && Object.assign(detail, { detailKey });
    detailValue >= 0 && Object.assign(detail, { detailValue });
    detailType >= 0 && Object.assign(detail, { detailType });
    dataFlag >= 0 && Object.assign(detail, { dataFlag });
    if (Object.keys(detail).length == 0) {
      return false;
    }
    var res;
    try {
      if (update) {
        res = await Details.update(detail, { where: whereOpt });
        if (res[0] > 0) {
          detail.detailId = detailId;
          return SON.parse(JSON.stringify(detail));
        } else {
          return false;
        }
      } else {
        res = await Details.create(detail);
        if (res.dataValues == undefined) {
          return false;
        } else {
          return JSON.parse(JSON.stringify(res.dataValues));
        }
      }
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  /* 
  批量添加
  */
  async  batchAddDetails(arr){
    if(!(arr instanceof Array) || arr.length == 0){
      return false;
    }
    var res;
    try {
      res = await Details.bulkCreate(arr,{
        fields:[
          "linkId",
          "detailKey",
          "detailValue",
          "detailType",
          "dataFlag"
        ]
      });
      return JSON.parse(JSON.stringify(res));
    } catch (error) {
      console.log(error);
      return null;
    }
  }
  //查询配置
  async getDetails({linkId}) {
    try {
      if(!linkId || !linkId){
        return false;
      }
      var res = await Details.findAll({where:{linkId,dataFlag:1},order:[['detailId',"ASC"]]});
      if(!res){
        return false;
      }
      if(res.length > 0){
        return JSON.parse(JSON.stringify(res.dataValues));
      }else{
        return [];
      }
    } catch (error) {
      console.log(error);
      return false;
    }
  }
  async eraseDetails({linkId,detailId}){
    var whereOpt = {};
    linkId && Object.assign(whereOpt,{linkId});
    detailId && Object.assign(whereOpt,{detailId});
    if(Object.keys(whereOpt).length == 0){
      return false;
    }
    var res;
    try {
      res = await Details.destroy({where:whereOpt});
      if(!res){
        return false;
      }else{
        return true;
      }
    } catch (error) {
      console.log(error);
      return null;
    }
  }
}

module.exports = new DetailsService();
